﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMC.Structs;

namespace PMC.Extensions.Default
{
    public partial class PTCForm : Form
    {
        private PTCWebsite _ptcWebsite;
        public PTCWebsite PtcWebsite
        {
            get { return _ptcWebsite; }
            set { _ptcWebsite = value; }
        }

        public PTCForm()
        {
            InitializeComponent();
            foreach (Website website in Website.Websites)
            {
                cbWebsites.Items.Add(website);
            }
            if (cbWebsites.Items.Count > 0)
                cbWebsites.SelectedIndex = 0;
            cbWebsites.DisplayMember = "Name";
            _ptcWebsite = new PTCWebsite();
            tbUrl.LostFocus += new EventHandler(tbUrl_LostFocus);
            //pnlWebsites.Controls.Add(new );
        }

        void tbUrl_LostFocus(object sender, EventArgs e)
        {
            foreach (Website item in cbWebsites.Items)
            {
                string host = item.Webpage.Host.Replace("www.", "");

                if (tbUrl.Text.IndexOf(host, StringComparison.OrdinalIgnoreCase) <= -1) 
                    continue;

                cbWebsites.SelectedItem = item;
                break;
            }
        }

        public PTCForm(PTCWebsite website)
            : this()
        {
            _ptcWebsite = website;
            tbUrl.Text = Convert.ToString(website.Url);
            cbWebsites.SelectedItem = website.Website;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!Uri.IsWellFormedUriString(tbUrl.Text, UriKind.Absolute))
            {
                MessageBox.Show("Given information is not a valid url.");
                DialogResult = DialogResult.None;
            }
            else if (cbWebsites.SelectedItem == null)
            {
                MessageBox.Show("Selected website is invalid!");
                DialogResult = DialogResult.None;
            }
            else
            {
                _ptcWebsite.Url = new Uri(tbUrl.Text);
                _ptcWebsite.Website = (Website)cbWebsites.SelectedItem;
            }
        }
    }
}
